import numpy as np
import cv2
from PIL import Image
from pylab import *
import os
import shutil
import get_LBP_from_Image
import psycopg2

# 计算两个向量之间的欧氏距离
def euclidean_distance(a, b):
    return np.linalg.norm(a - b)

# 计算图像相似度
def compute_similarity(query_vector, database_vector):
    # 将直方图特征向量转换为 NumPy 数组并添加为矩阵的第一行
    # 计算相似度
    # distance = euclidean_distance(query_vector, database_vector)
    # 将距离归一化到 [0, 1] 范围内
    # similarity = 1 / (1 + distance)
    similarity = euclidean_distance(query_vector, database_vector)
    return similarity

if __name__ == '__main__':

    conn = psycopg2.connect(
        host="YOUR_HOST",
        port="YOUR_PORT",
        user="YOUR_USER",
        password="YOUR_PASSWORD",
        database="YOUR_DATABASE"
    )

    cursor = conn.cursor()

    # 插入数据
    dataset_path = r"E:\IMDB\search"
    lbp = get_LBP_from_Image.LBP()

    for filename in os.listdir(dataset_path):
        if filename.endswith(".jpg") :
            image_path = os.path.join(dataset_path, filename)
            image_array = lbp.describe(image_path)

            # 获取图像原始LBP特征，并输出特征向量
            basic_array = lbp.lbp_basic(image_array)
            h0, _ = np.histogram(basic_array, bins=256, range=(0, 256))
    cursor.execute("SELECT count(*) FROM feature_vectors;")
    vectors_count = cursor.fetchall()

    dataset_path = r"E:\IMDB\wiki1"
    cursor.execute("SELECT id FROM feature_vectors;")
    id_list = cursor.fetchall()

    # 查询表中的所有 vector 列，并转换为 NumPy 数组
    cursor.execute("SELECT vector FROM feature_vectors;")
    vectors_list = cursor.fetchall()
    vectors_array = np.array([np.fromstring(vector[0][1:-1], sep=',') for vector in vectors_list])

    for i in range(len(vectors_list)):
        ceshi = compute_similarity(h0, vectors_array[i])
        update_query = "UPDATE feature_vectors SET distance = %s WHERE id = %s;"
        cursor.execute(update_query, (ceshi, id_list[i][0]))
        conn.commit()

    # 创建目标文件夹
    destination_folder = "E:\\IMDB\\search_uncut_20"
    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)

    # 查询搜索出的图片名
    cursor.execute("SELECT filename FROM feature_vectors ORDER BY distance ASC LIMIT 20;")
    search_filename_list = cursor.fetchall()

    # 将搜索出的图片复制到目标文件夹
    for i in range(20):
        filename = search_filename_list[i][0]
        image_path = os.path.join(dataset_path, filename)
        destination_path = os.path.join(destination_folder, filename)
        shutil.copy(image_path, destination_path)
        print(f"Moved {filename} to {destination_folder}")


    # 关闭连接
    cursor.close()
    conn.close